import {sign, state} from './dapp'

let t = function(msg) {
    return msg
};

function setLocate(tt) {
    t = tt
}

function showErr(res, notShowToast) {
    if (res.code !== 200) {
        if (res.code === 401 || res.code === 402) {
            localStorage.setItem('token', '');
        } else {
            if(!notShowToast){
                Toast(t(res.msg) + res.extendsMsg);
            }
        }
    }
}

async function get(url, notShowToast) {
    let headers = {
        'token': localStorage.getItem("token")
    };
    if (url.indexOf('?') === -1) {
        url += '?'
    }else{
        url += "&"
    }
    url += `address=${state.address}`;
    let res = await fetch(url, {headers}).then(res => res.json());
    showErr(res, notShowToast);
    return res
}
let pending = false;
async function post(url, noSign, cancelReact) {
    if(pending) return ;
    let signData = "";
    if(!noSign){
        signData = await sign(url, cancelReact);
    }
    let headers = {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'token': localStorage.getItem("token")
    };
    pending = true;
    let res = await fetch(url + signData, {method: 'POST', headers}).then(res => res.json().catch(() => {
        pending = false;
    }));
    pending = false;
    showErr(res);
    return res
}

export default {
    get, post,setLocate
}

